package com.recharge.sup.impl;


import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.recharge.OrderService;
import com.recharge.domain.TradeFlow;
import com.recharge.domain.TradeOrder;
import com.recharge.mapper.ITradeOrderMapper;
import com.recharge.sup.AbsSupChargeService;
import com.recharge.utils.HttpClientUtils;
import com.recharge.utils.ProcessResult;
import com.recharge.utils.ResultCodeHfQuXun;

/**
 * 趣讯话费对接
 * @author qq
 *
 */
@Service
public class QuXunHfChargeServiceImpl extends AbsSupChargeService {

	// 合作方编号
	@Value("${quxunhf.partnerNo}")
	private String partner_no;

	@Value("${quxunhf.queryBanlanceUrl}")
	private String queryBanlanceUrl;

	@Value("${quxunhf.sendHfUrl}")
	private String sendHfUrl;

	@Value("${quxunhf.queryStatusUrl}")
	private String queryStatusUrl;

	@Value("${quxunhf.queryCallBackUrl}")
	private String back_url;

	@Value("${quxunhf.key}")
	private String key;
	
	@Autowired
    private OrderService orderService;
	
	@Autowired
	private ResultCodeHfQuXun resultCodeHfQuXun;

	@Autowired
    private ITradeOrderMapper iTradeOrderMapper;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	//充值
	@Override
	public ProcessResult recharge(TradeOrder tradeOrder, TradeFlow tradeFlow) {
		String price = tradeOrder.getChargeMoney()+"";//金额
		String num  = "1";							 //商品数量
		String mobile = tradeOrder.getChargeNumber();//手机号码
		String spordertime = tradeOrder.getOrderTime()+"";//订单时间
		System.out.println("时间"+spordertime);
		String sporderid = tradeOrder.getOrderId();//订单id
		String result = "";
		String strSign= "userid="+partner_no+"&"+"price="+price+"&"+"num="+num
				+"&"+"mobile="+mobile+"&"+"spordertime="+spordertime+"&"+"sporderid="+sporderid
				+"&"+"key="+key;
		logger.info("orderid:{}发送趣讯话费sign:{}",sporderid, strSign );
		String sign = DigestUtils.md5Hex(strSign);
		Map<String,String> map = new HashMap<String, String>();
		map.put("userid", partner_no);
		map.put("price", price);
		map.put("num", num);
		map.put("mobile", mobile);
		map.put("spordertime", spordertime);
		map.put("sporderid", sporderid);
		map.put("sign", sign);
		map.put("back_url", back_url);
		try {
			result = HttpClientUtils.invokePostHttp(sendHfUrl, map, "UTF-8", 3000);
			logger.info("orderid:{}趣讯话费返回:{}",sporderid, result );
		} catch (Exception e) {
			e.printStackTrace();
		}
		Document document = null;
		try {
			document = DocumentHelper.parseText(result);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        String user = document.getRootElement().element("resultno").getText();
        if(user != null && !"".equals(user)){
        	if(user == "0"){
        		logger.info("orderid:{}趣讯话费,等待充值",sporderid );
        		iTradeOrderMapper.updateProcessStatus(sporderid, "等待充值");
        		ProcessResult processResult = new ProcessResult();
    	    	processResult.setCode(ProcessResult.PROCESSING);
            	return processResult;
        	}else if(user == "1"){
        		logger.info("orderid:{}趣讯话费,充值成功",sporderid );
        		iTradeOrderMapper.updateProcessStatus(sporderid, "充值成功");
        		ProcessResult processResult = new ProcessResult();
    	    	processResult.setCode(ProcessResult.SUCCESS);
            	return processResult;
        	}else if(user == "2"){
        		logger.info("orderid:{}趣讯话费,充值中",sporderid );
        		iTradeOrderMapper.updateProcessStatus(sporderid, "充值中");
        		ProcessResult processResult = new ProcessResult();
    	    	processResult.setCode(ProcessResult.PROCESSING);
            	return processResult;
        	}else{
        		String resultHf =  resultCodeHfQuXun.processResultCode(user);
        		logger.info("orderid:{}趣讯话费返回结果code:{}",sporderid,resultHf );
        		iTradeOrderMapper.updateProcessStatus(sporderid, resultHf);
        		ProcessResult processResult = new ProcessResult();
    	    	processResult.setCode(ProcessResult.FAIL);
            	return processResult;
        	}
        }
        iTradeOrderMapper.updateProcessStatus(sporderid,"发送失败");
	    logger.info("order_id:{}发送结果可疑",sporderid );        
        ProcessResult processResult = new ProcessResult();
        processResult.setCode(ProcessResult.UNKNOWN);   
        return processResult;
	}

	//回调
	@Override
	public void response(TradeOrder tradeOrder, TradeFlow tradeFlow, Map<String, String> responseMap) {
		String sporderid  = responseMap.get("sporderid");
		String resultno = responseMap.get("resultno");
		logger.info("order_id:{}回调resultNo:{}",sporderid ,resultno);
	    if (StringUtils.equals("1", resultno )){     
	         orderService.SUCCESS(tradeOrder,tradeFlow);
	    }else if (StringUtils.equals("9",resultno) || 
	    		StringUtils.equals("5001",resultno)||
	    		StringUtils.equals("5002",resultno)||
	    		StringUtils.equals("5003",resultno)||
	    		StringUtils.equals("5004",resultno)||
	    		StringUtils.equals("5005",resultno)||
	    		StringUtils.equals("5006",resultno)||
	    		StringUtils.equals("5007",resultno)||
	    		StringUtils.equals("5008",resultno)||
	    		StringUtils.equals("5009",resultno)||
	    		StringUtils.equals("5010",resultno)||
	    		StringUtils.equals("5011",resultno)||
	    		StringUtils.equals("5012",resultno)||
	    		StringUtils.equals("9999",resultno)){
	         orderService.FAIL(tradeOrder, tradeFlow); 
	    }else{
	         orderService.UNKNOWN(tradeOrder, tradeFlow);
	    }
	}

	//查询
	@Override
	public ProcessResult query(TradeOrder tradeOrder, TradeFlow tradeFlow) {
		String sporderid = tradeOrder.getOrderId();//商户订单号
		String result = "";
		String strSign= "userid="+partner_no+"&"+"sporderid="+sporderid;
				//+"&"+"key="+key;
		String sign = DigestUtils.md5Hex(strSign);//加密
		Map<String,String> map = new HashMap<String, String>();
		map.put("userid", partner_no);
		map.put("sporderid", sporderid);
		//map.put("sign", sign);
		try {
			result = HttpClientUtils.invokePostHttp(queryStatusUrl, map, "UTF-8", 3000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Document document = null;
		try {
			document = DocumentHelper.parseText(result);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
        String user = document.getRootElement().element("resultno").getText();
        if(user != null && !"".equals(user)){
        	if(user == "0"){
        		logger.info("orderid:{}查询趣讯话费,等待充值",sporderid );
        		iTradeOrderMapper.updateProcessStatus(sporderid, "等待充值");
        		ProcessResult processResult = new ProcessResult();
    	    	processResult.setCode(ProcessResult.PROCESSING);
            	return processResult;
        	}else if(user == "1"){
        		logger.info("orderid:{}查询趣讯话费,充值成功",sporderid );
        		iTradeOrderMapper.updateProcessStatus(sporderid, "充值成功");
        		ProcessResult processResult = new ProcessResult();
    	    	processResult.setCode(ProcessResult.SUCCESS);
            	return processResult;
        	}else if(user == "2"){
        		logger.info("orderid:{}查询趣讯话费,充值中",sporderid );
        		iTradeOrderMapper.updateProcessStatus(sporderid, "充值中");
        		ProcessResult processResult = new ProcessResult();
    	    	processResult.setCode(ProcessResult.PROCESSING);
            	return processResult;
        	}else{
        		String resultHf =  resultCodeHfQuXun.processResultCode(user);
        		logger.info("orderid:{}查询趣讯话费返回结果code:{}",sporderid,resultHf );
        		iTradeOrderMapper.updateProcessStatus(sporderid, resultHf);
        		ProcessResult processResult = new ProcessResult();
    	    	processResult.setCode(ProcessResult.FAIL);
            	return processResult;
        	}
        }
        iTradeOrderMapper.updateProcessStatus(sporderid,"查询失败");
	    logger.info("order_id:{}查询结果可疑",sporderid );       
        ProcessResult processResult = new ProcessResult();
        processResult.setCode(ProcessResult.UNKNOWN);  
        return processResult;
	}
	
	public static String encrypt(String input, String key, String vi) throws Exception { 
		 try {             
			 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
			 cipher.init(Cipher.ENCRYPT_MODE, 
					 new SecretKeySpec(key.getBytes(), "AES"), 
					 new IvParameterSpec(vi.getBytes())); 
			 byte[] encrypted = cipher.doFinal(input.getBytes("utf-8")); 
			// 此处使用 BASE64 做转码。             
			 return DatatypeConverter.printBase64Binary(encrypted); 
		 } catch (Exception ex) {             
			 return null; 
		 } 
	 }
	
	public static void main(String[] args) throws DocumentException {
		String userid = "200815";
		//String sporderid ="111111111";
		String key = "pVKVWC2Jh4Upikca0F17kZSwarCOshjj";
		String result = "";
		//String Strsign= "userid="+userid+"&"+"sporderid="+sporderid+"&"+"key="+key;
		String Strsign= "userid="+userid+"&"+"key="+key;
		String sign = DigestUtils.md5Hex(Strsign);
		System.out.println("字符签名"+Strsign);
		System.out.println("其他签名"+sign);
		Map<String, String> map = new HashMap<String, String>();
		map.put("userid", userid);
		//map.put("sporderid", sporderid);//invokePostHttp
		map.put("sign", sign);

		try {
			result = HttpClientUtils.invokePostHttp("http://test.e7chong.com:8899/balance.do", map, "UTF-8", 3000);
			System.out.println("这是"+result);
			Document doc = DocumentHelper.parseText(result);
			
            String user = doc.getRootElement().element("userid").getText();
            System.out.println(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
